package update

import (
	"fmt"
	"go-xorm/model"
	"xorm.io/xorm"
)

func Update(engine *xorm.Engine) {
	var user model.User
	user.UserName = "Bob"
	affected, err := engine.ID(user.Id).Update(&user)
	fmt.Println(affected, err)

	// 只更新特定字段
	affected, err = engine.ID(1).Cols("name").Update(&model.User{UserName: "Bob"})
	fmt.Println(affected, err)
}

func trans(engine *xorm.Engine) error {
	session := engine.NewSession()
	defer session.Close()

	if err := session.Begin(); err != nil {
		return err
	}

	if _, err := session.Insert(&model.User{UserName: "Alice"}); err != nil {
		session.Rollback()
		return err
	}

	if _, err := session.Insert(&model.User{UserName: "Bob"}); err != nil {
		session.Rollback()
		return err
	}

	return session.Commit()
}
